package com.itsq.service.resources.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itsq.common.bean.ErrorEnum;
import com.itsq.common.constant.APIException;
import com.itsq.mapper.CarMapper;
import com.itsq.mapper.PersonnelMapper;
import com.itsq.pojo.dto.PageUsagerecordDto;
import com.itsq.pojo.dto.UsageRecordEndDto;
import com.itsq.pojo.entity.Car;
import com.itsq.pojo.entity.Department;
import com.itsq.pojo.entity.Personnel;
import com.itsq.pojo.entity.UsageRecord;
import com.itsq.mapper.UsageRecordMapper;
import com.itsq.service.resources.UsageRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 史先帅
 * @since 2021-01-30
 */
@Service
public class UsageRecordServiceImpl extends ServiceImpl<UsageRecordMapper, UsageRecord> implements UsageRecordService {

    @Autowired(required = false)
    private UsageRecordMapper usageRecordMapper;

    @Autowired(required = false)
    private CarMapper carMapper;

    @Autowired(required = false)
    private PersonnelMapper personnelMapper;

    @Override
    public Page<UsageRecord> selUsageRecordPageFront(PageUsagerecordDto pageUsagerecordDto) {
        Page<UsageRecord> page = new Page<>(pageUsagerecordDto.getPageIndex(), pageUsagerecordDto.getPageSize());
        QueryWrapper queryWrapper = new QueryWrapper();
        if (pageUsagerecordDto.getOrderByField() != null) {
            queryWrapper.orderByDesc("cre_date");
        } else {
            queryWrapper.orderByDesc(pageUsagerecordDto.getOrderByField());
        }
        if(pageUsagerecordDto.getUserId()!=null){
            queryWrapper.eq("user_id",pageUsagerecordDto.getUserId());
        }
        if(pageUsagerecordDto.getCarId()!=null){
            queryWrapper.eq("car_id",pageUsagerecordDto.getCarId());
        }
        return usageRecordMapper.selectPage(page, queryWrapper);
    }

    @Override
    public Page<UsageRecord> selUsageRecordPageAfter(PageUsagerecordDto pageUsagerecordDto) {
        Page<UsageRecord> page = new Page<>(pageUsagerecordDto.getPageIndex(), pageUsagerecordDto.getPageSize());
        QueryWrapper queryWrapper = new QueryWrapper();
        if (pageUsagerecordDto.getOrderByField() == null) {
            queryWrapper.orderByDesc("cre_date");
        } else {
            queryWrapper.orderByDesc(pageUsagerecordDto.getOrderByField());
        }
        if(pageUsagerecordDto.getUserId()!=null){
            queryWrapper.eq("user_id",pageUsagerecordDto.getUserId());
        }
        if(pageUsagerecordDto.getCarId()!=null){
            queryWrapper.eq("car_id",pageUsagerecordDto.getCarId());
        }
        return usageRecordMapper.selectPage(page, queryWrapper);
    }

    @Override
    public Page<UsageRecord> selUsageRecordById(PageUsagerecordDto pageUsagerecordDto) {
        Page<UsageRecord> page = new Page<>(pageUsagerecordDto.getPageIndex(), pageUsagerecordDto.getPageSize());
        QueryWrapper queryWrapper = new QueryWrapper();
        if(pageUsagerecordDto.getUserId() != null){
            queryWrapper.eq("user_id",pageUsagerecordDto.getUserId());
        }
        if (pageUsagerecordDto.getOrderByField() == null) {
            queryWrapper.orderByDesc("cre_date");
        } else {
            queryWrapper.orderByDesc(pageUsagerecordDto.getOrderByField());
        }
        Page page1 = usageRecordMapper.selectPage(page, queryWrapper);
        return page1;
    }

    @Override
    public UsageRecord insertBegin(UsageRecord usageRecord) {

        //获取用户id
        //Integer userId = usageRecord.getUserId();
        //通过用户id获取权限
//        Personnel personnel = personnelMapper.selectById(userId);
//        Integer isOk = personnel.getIsOk();
//        if(isOk<1){
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("car_id",usageRecord.getCarId());
            queryWrapper.eq("states",0);
            UsageRecord usageRecord1 = super.baseMapper.selectOne(queryWrapper);
            QueryWrapper queryWrapper1=new QueryWrapper();
            queryWrapper1.eq("user_id",usageRecord.getCarId());
            queryWrapper1.eq("states",0);
            UsageRecord usageRecord2 = super.baseMapper.selectOne(queryWrapper);
            if(usageRecord1!=null){
                throw new APIException(ErrorEnum.CUNZAI);
            }
            if(usageRecord2!=null){
                throw new APIException(ErrorEnum.USERCAR);
            }
            //判断是否有已存在租车
            QueryWrapper queryWrapper3=new QueryWrapper();
            queryWrapper3.eq("car_id",usageRecord.getCarId());
            List<UsageRecord> list = usageRecordMapper.selectList(queryWrapper3);
//            UsageRecord usageRecord3 = usageRecordMapper.selectById(usageRecord.getUserId());
            for (int i = 0; i < list.size(); i++) {
                if(list.get(i).getEndDate()==null){
                    throw new APIException(ErrorEnum.is_ISNULL);
                }
            }
            //添加
            int i = usageRecordMapper.insert(usageRecord);

            if (i < 1) {
                throw new APIException(ErrorEnum.is_ISNULL);
            }
            return usageRecord;
//        }
//        return null;
    }

    @Override
    public List<UsageRecord> selUsageRecordStatus(UsageRecord usageRecord) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if(usageRecord.getId()!=null){
            queryWrapper.eq("car_id",usageRecord.getCarId());
        }
        if(usageRecord.getUserId()!=null){
            queryWrapper.eq("user_id",usageRecord.getUserId());
        }
        if(usageRecord.getStates()!=null){
            queryWrapper.eq("states",usageRecord.getStates());
        }
        return usageRecordMapper.selectList(queryWrapper);
    }

    @Override
    public Integer updateEnd(UsageRecordEndDto usageRecordEndDto) {
        Car car = carMapper.selectById(usageRecordEndDto.getCarId());
        Double money = car.getMoney();
        //通过id获取使用记录对象
        UsageRecord usageRecord = usageRecordMapper.selectById(usageRecordEndDto.getId());
        usageRecord.setStates(1);
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取当前时间
        String format = df.format(new Date());

        try {
            //结束时间
            Date parse = df.parse(format);
            //起始时间
            String s = df.format(usageRecord.getCreDate());
            Date parse1 = df.parse(s);
            //计算使用时间
            long diff= parse.getTime() - parse1.getTime();
            //转换分钟
            long minutes = TimeUnit.MILLISECONDS.toMinutes(diff)+1;
            //向上取整
            double ceil = Math.ceil(minutes);
            //计算费用
            double m =ceil*money;
            //修改耗时
            usageRecord.setMinutes(minutes);
            //修改价钱
            usageRecord.setMoney(m);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        usageRecord.setEndDate(new Date());
        Integer i = usageRecordMapper.updateById(usageRecord);
        if (i < 1) {
            throw new APIException(ErrorEnum.is_UPDATE);
        }
        return i;
    }

    @Override
    public Integer update(UsageRecord usageRecord) {
        return usageRecordMapper.updateById(usageRecord);
    }

    @Override
    public Integer status(UsageRecord usageRecord) {
        int i=0;
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",usageRecord.getUserId());
        List<UsageRecord> list = usageRecordMapper.selectList(queryWrapper);
        for (UsageRecord record : list) {
            if(record.getEndDate()==null){
                i=1;
            }
        }
        return i;
    }


}
